package com.example.admin.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.admin.SysDepartment;
import com.example.admin.SysDeptRole;
import com.example.admin.SysRole;
import com.example.admin.SysUser;
import com.example.admin.service.ISysDepartmentService;
import com.example.admin.service.ISysDeptRoleService;
import com.example.admin.service.ISysRoleService;
import com.example.shrio.CurrentUser;
import com.example.admin.service.impl.DataScope;
import com.example.util.APIState;
import com.example.util.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wangkai
 * @since 2019-06-04
 */
@RestController
@Api(value = "部门管理Controller", tags = {"部门管理操作接口"})
@RequestMapping("/sys/sysDepartment")
public class SysDepartmentController {

    @Autowired
    private ISysDepartmentService service;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptRoleService deptRoleService;

    @Autowired
    private DataScope dataScope;

    @ApiOperation(value = "部门管理列表", httpMethod = "POST")
    @PostMapping(value = "/page")
    public AjaxResult page() {
        QueryWrapper<SysDepartment> queryWrapper = new QueryWrapper<SysDepartment>();
        queryWrapper.orderByAsc("type");
        SysUser sysUser = CurrentUser.getAdminUser();
        if (!sysUser.getAccount().equals("admin")) {
            queryWrapper.eq("create_by", sysUser.getId());
            List<SysDepartment> result = new ArrayList<>();
            result.addAll(service.list(queryWrapper));
            result.add(service.getById(sysUser.getDeptId()));
            return new AjaxResult(APIState.S00, result);
        }
        return new AjaxResult(APIState.S00, service.list(queryWrapper));
    }

    @ApiOperation(value = "部门管理list", httpMethod = "GET")
    @GetMapping(value = "/list/{roleId}")
    public AjaxResult getList(@PathVariable Integer roleId) {
        SysRole sysRole = roleService.getById(roleId);
        if (sysRole == null) {
            return new AjaxResult(APIState.S01, "该角色不存在");
        }
        List<Integer> deptIds = new ArrayList<>();
        if (sysRole.getDataScope() == 0) {
            QueryWrapper<SysDeptRole> queryWrapper = new QueryWrapper<>();
            List<SysDeptRole> deptRoles = deptRoleService.list(queryWrapper);
            if (deptRoles != null && deptRoles.size() > 0) {
                deptIds.addAll(deptRoles.stream().map(info -> info.getDeptId()).collect(Collectors.toList()));
            }
        }
        QueryWrapper<SysDepartment> queryWrapper = new QueryWrapper<SysDepartment>();
        queryWrapper.orderByAsc("type");
        List<SysDepartment> list = service.list(queryWrapper);
        JSONObject result = new JSONObject();
        result.put("tree", list);
        result.put("nodeData", deptIds);
        return new AjaxResult(APIState.S00, result);
    }

    @ApiOperation(value = "用户部门list", httpMethod = "GET")
    @GetMapping(value = "/userList")
    public AjaxResult getUserList() {
        QueryWrapper<SysDepartment> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("type");
        SysUser sysUser = CurrentUser.getAdminUser();
        List<SysDepartment> list = new ArrayList<>();
        if (!sysUser.getAccount().equals("admin")) {
            queryWrapper.eq("create_by", sysUser.getId());
            list.add(service.getById(sysUser.getDeptId()));
        }
        dataScope.dataScope(queryWrapper);
        list.addAll(service.list(queryWrapper));
        return new AjaxResult(APIState.S00, list);
    }


    /**
     * 保存
     *
     * @param sysDepartment
     * @return
     */
    @ApiOperation(value = "部门管理新增", httpMethod = "POST")
    @PostMapping
    public AjaxResult save(@RequestBody SysDepartment sysDepartment) {
        if (sysDepartment != null) {
            sysDepartment.setCreateBy(String.format("%s", CurrentUser.getAdminUser().getId()));
            sysDepartment.setCreateTime(new Date());
            if (sysDepartment.insert()) {
                return new AjaxResult(APIState.S00, "保存成功");
            }
        }
        return new AjaxResult(APIState.S01, "保存失败");
    }

    /**
     * 修改
     *
     * @param sysDepartment
     * @return
     */
    @ApiOperation(value = "部门管理编辑", httpMethod = "PUT")
    @PutMapping
    public AjaxResult update(@RequestBody SysDepartment sysDepartment) {
        if (sysDepartment != null && sysDepartment.getId() != null) {
            sysDepartment.setUpdateBy(String.format("%s", CurrentUser.getAdminUser().getId()));
            sysDepartment.setUpdateTime(new Date());
            if (sysDepartment.insertOrUpdate()) {
                return new AjaxResult(APIState.S00, "保存成功");
            }
        }
        return new AjaxResult(APIState.S01, "保存失败");
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "部门管理删除", httpMethod = "DELETE")
    @DeleteMapping(value = "/{id}")
    public AjaxResult delete(@PathVariable Long id) {
        if (id != null) {
            SysDepartment sysDepartment = service.getById(id);
            if (sysDepartment != null) {
                if (sysDepartment.deleteById()) {
                    return new AjaxResult(APIState.S00, "删除成功");
                }
            } else {
                return new AjaxResult(APIState.S01, "当前部門不存在请重新刷新列表");
            }
        }
        return new AjaxResult(APIState.S01, "删除失败");
    }

}
